/**
 * 
 */
package com.evil.Utils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


/******************************************
 * 工程名：HelloYouth<br>
 * 包名：com.evil.Utils<br>
 * 时间：2016年6月12日 下午8:37:57<br>
 * 作者：白雨濃 evil<br>
 * 邮箱：evilbai@foxmail.com<br>
 * 内容：图片输出总类，传入图片名称，获得图片<br>
 ******************************************/
public class GetImage extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setContentType("text/hmtl;charset=utf-8");

		String itemImg = request.getParameter("img");
		//System.out.println("图片："+itemImg);

		String imgUrl = "/image/" + itemImg;
		

		outbitmap(getServletContext(), response, imgUrl);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		this.doGet(request, response);
	}

	private void outbitmap(ServletContext servletContext,
			HttpServletResponse response, String imgUrl) throws IOException
	{
		//String path = this.servletContext.getRealPath("/image/content_films.jpeg");
		//得到真实的地址
		String path = servletContext.getRealPath(imgUrl);
		String fileName = path.substring(path.lastIndexOf("\\") + 1);
		//System.out.println(fileName);

		response.setHeader("content-disposition", "attachment;fileName="
				+ fileName);
		InputStream reader = null;
		ServletOutputStream sout = null;
		byte[] bytes = new byte[1024];
		int len = 0;
		try
		{
			// 读取文件
			reader = new FileInputStream(path);
			// 写入浏览器的输出流

			sout = response.getOutputStream();
			while ((len = reader.read(bytes)) > 0)
			{
				sout.write(bytes, 0, len);
			}
			sout.flush();
		}
		catch (Exception e)
		{
			System.out.println(imgUrl + "ID未找到");
		}
		finally
		{
			if (reader != null)
				reader.close();
			if (sout != null)
				sout.close();
		}
	}

}
